import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { clearSearchResultAction, getSearchResultAction } from '@/store/action/search';
import { useAppDispatch, useAppSelector } from '@/store';
import { InfiniteScroll, Toast } from 'antd-mobile';
import { Result } from '@/store/reducer/search';

export default function SearchResult() {
  const dispatch = useAppDispatch();
  const { resultData } = useAppSelector((state) => state.search);
  //获取跳转携带的参数
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  const keyword = params.get('keyword');
  //加载更多
  const loadMore = async () => {
    //触发加载更多
    // await dispatch(getMoreSearchResultAction(keyword as string, resultData.page + 1));
    //优化 代码复用
    await dispatch(getSearchResultAction(keyword as string, resultData.page + 1));
  };
  useEffect(() => {
    //判断参数是否为空
    if (!keyword) {
      Toast.show({ content: '查询参数不能为空' });
      return;
    }
    //获取搜索结果
    dispatch(getSearchResultAction(keyword));
    //清除搜索结果
    return () => {
      dispatch(clearSearchResultAction());
    };
  }, [keyword]);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {resultData.results?.map((item: Result) => {
          return <ArticleItem key={item.art_id} data={item} />;
        })}
      </div>
      {/* 无限滚动 */}
      {/* 逻辑判断是否渲染无限滚动组件 */}
      {
        <InfiniteScroll
          loadMore={loadMore}
          // 存储数据的数组长度小于总数时，才会触发加载更多
          hasMore={resultData.results?.length < resultData.total_count}
        ></InfiniteScroll>
      }
    </div>
  );
}
